<?php

namespace app\index\controller;

use think\exception\ValidateException;
use app\model\Tuanzhang;
use app\model\Category;
use app\model\Order;
use app\model\Store;
use app\model\UsersRelation;

class AdmintuanzhangController extends Base
{

	public function check()
	{
		$message = '';
		$is_login = 0;

		$data = Tuanzhang::getInfobyuid(UID());

		if ($data['status'] != 1) {
			$data = 0;
			$message = '请先登录！';
		} else {
			$this->userInfo['tzid'] = $data['id'];
            $this->setAppToken($this->userInfo, $this->getAppToken());
			$is_login = 1;
		}
		return $this->json(['message' => $message, 'is_login' => $is_login, 'data' => $data]);
	}
	public function setstorelogin()
	{
		$datatz = Tuanzhang::getInfobyuid(UID());
		if (!empty($datatz)) {
			$Store = Store::getStorebytzid($datatz['id']);
			Store::where('id', $Store['id'])->update(['status' => 1]);
			UsersRelation::create(['weid' => weid(), 'ptype' => 'store', 'reid' => (int) $Store['id'], 'uid' => (int) $Store['uid'], 'mid' => UID()]);
		}
		return $this->json(['msg' => '操作成功', 'data' => $datatz, 'Store' => $Store]);
	}
	public function business()
	{
		$id = $this->request->post('id');

		$Tuanzhang = Tuanzhang::find($id);

		if ($Tuanzhang->is_business == 1) {
			$Tuanzhang->is_business = 0;
		} else {
			$Tuanzhang->is_business = 1;
		}

		try {
			$Tuanzhang->save();
			$data = $Tuanzhang->toArray();
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}
		return $this->json(['msg' => '操作成功', 'data' => $data]);
	}

	public function update()
	{
		$id = $this->request->post('id');
		$data = input('post.');

		try {
			Tuanzhang::update($data);
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}
		return $this->json(['msg' => '修改成功']);
	}

	function getInfo()
	{
		$id = UsersRelation::getreid(UID(), 'tuanzhang');
		$data = Tuanzhang::find($id)?->toArray();
		if (empty($data)) {
			$data = Tuanzhang::where(['uid' => UID()])->find()?->toArray();
		}

		if (!empty($data)) {
			//空判定
			if (empty($data['cate_ids'])) {
				$data['cate_ids'] = [];
			} else {
				$data['cate_ids'] = explode(',', $data['cate_ids']);
			}
			$data['Category'] = Category::gettoparray();
		}



		return $this->json(['data' => $data]);
	}
}
